import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'

Vue.use(VueRouter)

// 将编程式导航调用 push() 时可能报错的异常静默处理
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location, onSuccess, onFail) {
  if (onSuccess || onFail) {
    return originalPush.call(this, location, onSuccess, onFail)
  }
  return originalPush.call(this, location).catch(() => {})
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const permissionRoutes = ['/order']
router.beforeEach((to, from, next) => {
  if (permissionRoutes.includes(to.path)) {
    if (JSON.parse(localStorage.getItem('userInfo'))) {
      next()
    } else {
      next({
        name: 'login'
      })
    }
  } else {
    next()
  }
})

export default router
